<template>
	<el-drawer 
		class="chat-history-drawer" 
		v-model="dialogVisible" 
		:size="mysize"
		direction="rtl"
		:modal="false"
		:with-header="false"
		:close-on-click-modal="false"
		:destroy-on-close="true"
		@opened="handleOpened">
		<div class="chat-history-container">
			<!-- 顶部导航栏 -->
			<div class="chat-history-header">
				<div class="header-title">
					<span>聊天历史记录</span>
				</div>
				<div class="header-actions">
					<el-button type="primary" size="small" circle @click="refreshMessages" :disabled="loading">
						<el-icon><Refresh /></el-icon>
					</el-button>
					<el-button type="default" size="small" circle @click="onClose">
						<el-icon><Close /></el-icon>
					</el-button>
				</div>
			</div>
			
			<!-- 聊天内容区域 -->
			<div class="chat-history-content" v-loading="loading" element-loading-text="加载中..." element-loading-background="rgba(255, 255, 255, 0.7)">
				<!-- 下拉加载提示 -->
				<div v-if="messages.length > 0 && !loadAll" class="load-more-hint" @click="loadMessages">
					<el-icon><ArrowUp /></el-icon>
					<span>点击加载更多</span>
				</div>
				
				<!-- 已到顶部提示 -->
				<div v-if="loadAll && messages.length > 0" class="load-all-hint">
					<span>已显示全部历史消息</span>
				</div>
				
				<!-- 消息列表 -->
				<div class="message-list" ref="messageList" v-if="messages.length > 0">
					<div v-for="(msgInfo, idx) in messages" :key="idx" 
						 class="message-item" 
						 :class="{'message-mine': msgInfo.sendId == mine.id}">
						<!-- 消息内容 -->
						<div class="message-content">
							<div class="message-bubble">
								<chat-message-item 
									:mode="2" 
									:mine="msgInfo.sendId == mine.id" 
									:headImage="headImage(msgInfo)" 
									:showName="showName(msgInfo)"
									:msgInfo="msgInfo" 
									:menu="false" 
									:tagId="idx"
									:hideAvatar="true">
								</chat-message-item>
							</div>
							<div class="message-time">{{ formatTime(msgInfo.sendTime) }}</div>
						</div>
					</div>
				</div>
				
				<!-- 空消息提示 -->
				<div v-if="!loading && messages.length === 0" class="empty-history">
					<el-icon><ChatDotSquare /></el-icon>
					<span>暂无历史聊天记录</span>
				</div>
			</div>
		</div>
	</el-drawer>
</template>

<script>
	import ChatMessageItem from './ChatMessageItem.vue';
	import { Refresh, ChatDotSquare, ArrowUp, Close } from '@element-plus/icons-vue';

	export default {
		name: 'chatHistory',
		components: {
			ChatMessageItem,
			Refresh,
			ChatDotSquare,
			ArrowUp,
			Close
		},
		props: {
			visible: {
				type: Boolean,
				default: false
			},
			chat: {
				type: Object,
				required: true
			},
			friend: {
				type: Object,
				default: () => ({})
			},
			group: {
				type: Object,
				default: () => ({})
			},
			groupMembers: {
				type: Array,
				default: () => []
			},
			mysize:{
				type: String,
				default: "600px"
			}
		},
		emits: ['update:visible', 'close'],
		data() {
			return {
				page: 1,
				size: 15,
				messages: [],
				loadAll: false,
				loading: false,
				lastScrollTime: new Date()
			}
		},
		computed: {
			dialogVisible: {
				get() {
					return this.visible;
				},
				set(value) {
					this.$emit('update:visible', value);
					if (!value) {
						this.$emit('close');
					}
				}
			},
			mine() {
				return this.$store.state.userStore.userInfo;
			},
			histroyAction() {
				return `/message/${this.chat.type.toLowerCase()}/history`;
			}
		},
		methods: {
			formatTime(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const now = new Date();
				const isToday = date.toDateString() === now.toDateString();
				
				// 格式化小时和分钟，确保两位数
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				
				if (isToday) {
					return `${hours}:${minutes}`;
				} else {
					const month = (date.getMonth() + 1).toString().padStart(2, '0');
					const day = date.getDate().toString().padStart(2, '0');
					return `${month}-${day} ${hours}:${minutes}`;
				}
			},
			onClose() {
				this.page = 1;
				this.messages = [];
				this.loadAll = false;
				this.$emit('close');
			},
			handleOpened() {
				console.log('抽屉完全打开，确保加载历史消息');
				if (this.messages.length === 0 && !this.loading && !this.loadAll) {
					this.loadMessages();
				}
			},
			loadMessages() {
				if (this.loadAll) {
					return this.$message.info("已显示全部历史消息");
				}
				
				if (this.loading) {
					console.log('已在加载中，跳过重复请求');
					return;
				}
				
				console.log('开始加载历史消息', {
					page: this.page,
					size: this.size,
					chatType: this.chat.type,
					chatId: this.chat.type === 'GROUP' ? (this.group && this.group.id ? this.group.id : 'unknown') : (this.friend && this.friend.id ? this.friend.id : 'unknown')
				});
				
				let param = {
					page: this.page++,
					size: this.size
				}
				if (this.chat.type == 'GROUP') {
					if (!this.group || !this.group.id) {
						console.error('群组信息不完整，无法加载历史消息');
						this.loading = false;
						this.$message.error('无法加载群聊历史消息，群组信息不完整');
						return;
					}
					param.groupId = this.group.id;
				} else {
					if (!this.friend || !this.friend.id) {
						console.error('好友信息不完整，无法加载历史消息');
						this.loading = false;
						this.$message.error('无法加载聊天历史消息，好友信息不完整');
						return;
					}
					param.friendId = this.friend.id;
				}
				
				this.loading = true;
				this.$http({
					url: this.histroyAction,
					method: 'get',
					params: param
				}).then(messages => {
					console.log('历史消息加载成功，数据条数:', messages?.length);
					
					if (messages && Array.isArray(messages)) {
						// 确保消息按时间顺序显示（从早到晚）
						const sortedMessages = [...messages].sort((a, b) => {
							return new Date(a.sendTime) - new Date(b.sendTime);
						});
						
						// 将排序后的消息添加到列表前面
						sortedMessages.forEach(m => this.messages.unshift(m));
						
						if(messages.length < this.size){
							this.loadAll = true;
						}
						
						// 确保UI更新后才执行滚动操作
						this.$nextTick(() => {
							this.scrollToPosition();
						});
					} else {
						console.error('收到的消息格式不正确:', messages);
						this.$message.error('加载历史记录失败');
						this.loadAll = true;
					}
					
					this.loading = false;
				}).catch((error) => {
					console.error('加载历史记录错误:', error);
					this.$message.error('加载历史记录失败');
					this.loading = false;
				});
			},
			scrollToPosition() {
				// 如果是第一页加载，滚动到底部
				if (this.page === 2) {
					this.$nextTick(() => {
						const messageList = this.$refs.messageList;
						if (messageList) {
							messageList.scrollTop = messageList.scrollHeight;
						}
					});
				}
			},
			showName(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member ? member.showNickName : "未知用户";
				} else {
					return msgInfo.sendId == this.mine.id ? this.mine.nickName : this.chat.showName;
				}
			},
			headImage(msgInfo) {
				if (this.chat.type == 'GROUP') {
					let member = this.groupMembers.find((m) => m.userId == msgInfo.sendId);
					return member ? member.headImage : "";
				} else {
					return msgInfo.sendId == this.mine.id ? this.mine.headImage : this.chat.headImage;
				}
			},
			refreshMessages() {
				this.page = 1;
				this.messages = [];
				this.loadAll = false;
				this.loadMessages();
			}
		},
		watch: {
			visible: {
				handler(newValue) {
					if (newValue) {
						this.page = 1;
						this.messages = [];
						this.loadAll = false;
						
						this.loadMessages();
					}
				},
				immediate: true
			}
		},
		mounted() {
			if (this.visible && this.messages.length === 0) {
				console.log('组件挂载，检测到visible为true，尝试加载消息');
				this.loadMessages();
			}
		},
		beforeDestroy() {
			// 清理工作
		}
	}
</script>

<style lang="scss">
	.chat-history-drawer {
		.el-drawer__body {
			padding: 0;
			overflow: hidden;
		}
		
		.el-drawer {
			overflow: hidden;
		}
	}
	
	.chat-history-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		background-color: #f7f7f7;
		
		.chat-history-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 10px 16px;
			background-color: #fff;
			border-bottom: 1px solid #e4e7ed;
			box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
			z-index: 1;
			
			.header-title {
				font-size: 16px;
				font-weight: 600;
				color: #303133;
			}
			
			.header-actions {
				display: flex;
				gap: 8px;
			}
		}
		
		.chat-history-content {
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
			position: relative;
			
			.load-more-hint, .load-all-hint {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 8px 0;
				font-size: 12px;
				color: #909399;
				background-color: rgba(220, 220, 220, 0.3);
				
				.el-icon {
					margin-right: 4px;
					font-size: 14px;
				}
			}
			
			.load-more-hint {
				cursor: pointer;
				transition: background-color 0.3s;
				
				&:hover {
					background-color: rgba(220, 220, 220, 0.5);
				}
			}
			
			.message-list {
				flex: 1;
				overflow-y: auto;
				padding: 10px 15px;
				
				/* 深度选择器，确保能穿透到子组件 */
				:deep(.el-avatar) {
					display: none !important;
				}
				
				:deep(.message-content-text) {
					padding: 6px 12px;
					background-color: #fff !important;
					border-radius: 4px;
					box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
				}
				
				:deep(.message-mine .message-content-text) {
					background-color: #ecf5ff !important;
				}
				
				:deep(.chat-bubble) {
					background-color: transparent !important;
					padding: 0 !important;
					box-shadow: none !important;
				}
				
				.message-item {
					display: flex;
					margin-bottom: 16px;
					
					&.message-mine {
						justify-content: flex-end;
						
						.message-content {
							align-items: flex-end;
							
							.message-sender {
								text-align: right;
							}
							
							.message-time {
								text-align: right;
							}
						}
					}
					
					.message-content {
						display: flex;
						flex-direction: column;
						max-width: 85%;
						
						.message-sender {
							font-size: 12px;
							color: #606266;
							margin-bottom: 2px;
						}
						
						.message-bubble {
							position: relative;
							border-radius: 4px;
							word-break: break-word;
							
							:deep(.chat-message-item) {
								.message-content {
									background: transparent !important;
								}
								
								.chat-message-container {
									padding: 0;
									margin: 0;
								}
							}
						}
						
						.message-time {
							font-size: 11px;
							color: #909399;
							margin-top: 2px;
						}
					}
				}
			}
			
			.empty-history {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				height: 100%;
				color: #909399;
				
				.el-icon {
					font-size: 48px;
					margin-bottom: 12px;
					color: #c0c4cc;
				}
				
				span {
					font-size: 14px;
				}
			}
		}
	}
</style>
